<template>
  <div class="app-container">
    <el-form
      ref="listFilterRef"
      :model="list.filter"
      inline
      class="list-filter"
    >
      <el-form-item prop="name">
        <el-input v-model="list.filter.name" placeholder="场次名称" clearable />
      </el-form-item>

      <el-form-item prop="groupId">
        <KiSelect
          v-model="list.filter.groupId"
          placeholder="所属活动"
          :options="activityList"
          :props="{ value: 'id', label: 'name' }"
        />
      </el-form-item>

      <el-form-item prop="status">
        <Status v-model="list.filter.status" />
      </el-form-item>
      <el-form-item prop="sessionType">
        <KiSelect
          v-model="list.filter.sessionType"
          placeholder="场次类型"
          :options="sessionTypes"
        />
      </el-form-item>

      <el-form-item prop="sessionStatus">
        <KiSelect
          v-model="list.filter.sessionStatus"
          placeholder="场次状态"
          :options="sessionStatusList"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-operation">
      <auth-button @click="c()" name="新增" />
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
        :pageSize.sync="list.filter.pageSize"
      />
    </div>

    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column align="center" type="index" />
      <el-table-column label="场次名称" prop="name" />
      <el-table-column label="所属活动" prop="name">
        <template slot-scope="{ row }">
          {{ row.groupList.map(g => g.name).join(' ') }}
        </template>
      </el-table-column>
      <el-table-column label="场次类型" prop="sessionType">
        <template slot-scope="{ row }">
          {{ row.sessionType | $value2label(sessionTypes) }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" prop="startTime" />
      <el-table-column label="结束时间" prop="endTime">
        <template slot-scope="{ row }">
          <div>{{ row.endTime }}</div>
          <el-tag :type="row.sessionStatusType" size="small">
            {{ row.sessionStatusName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column label="创建人" prop="createUserInfo.name" />
      <el-table-column label="启用状态" width="80" align="center">
        <template slot-scope="{ row: { id, status } }">
          <KiPopSwitch
            v-bind="popSwitchProps(status)"
            @change="updateStatus({ id, status: status ^ 1 })"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="{ row }">
          <auth-button @click="r(row)" name="查看" />
          <auth-button
            @click="u(row)"
            name="编辑"
            v-if="row.sessionStatusValue == '0'"
          />
          <auth-button @click="d(row)" name="删除" />
        </template>
      </el-table-column>
    </el-table>

    <KiFormDialog
      :show.sync="form.show"
      :title="formTitle"
      v-model="form.data"
      :submit="submit"
      :readonly="form.status === 'r'"
      ref="formRef"
      :loading="form.loading"
    >
      <template #el-form>
        <el-form-item label="所属活动" prop="groupId" verify>
          <KiSelect
            v-model="form.data.groupId"
            placeholder="请选择所属活动"
            :options="activityList"
            :props="{ value: 'id', label: 'name' }"
          />
        </el-form-item>

        <el-form-item label="场次名称" prop="name" verify>
          <el-input
            v-model="form.data.name"
            clearable
            maxlength="30"
            show-word-limit
            placeholder="请输入场次名称"
          />
        </el-form-item>
        <el-form-item label="场次类型" prop="sessionType" verify>
          <KiSelect
            v-model="form.data.sessionType"
            placeholder="请选择场次类型"
            :options="sessionTypes"
            @change="form.data.couponIdList = []"
          />
        </el-form-item>
        <el-form-item label="关联券" prop="couponIdList" verify>
          <el-button type="primary" @click="handleAddCoupon">
            <i class="el-icon-circle-plus-outline"></i>
            添加券
          </el-button>
          <ul class="info-warning">
            <li>优惠券需要在满减券中新增</li>
            <li>优惠券建议配置在5张以下，且不要使用其他用过的优惠券</li>
            <li>场次在进行中时，不要调整关联的优惠券</li>
            <li>若优惠券只有一张，请使用【固定发券】类型</li>
            <li>【固定发券】时，关联的券数量必须相同</li>
          </ul>
        </el-form-item>

        <div class="coupon-list">
          <el-row
            :gutter="10"
            v-for="(item, index) in form.data.couponIdList"
            v-if="item"
            :key="index"
            class="mb-15px"
          >
            <el-col :span="8">
              <el-form-item
                label="选择券"
                :prop="`couponIdList.${index}.couponId`"
                verify
              >
                <KiSelect
                  v-model="item.couponId"
                  placeholder="请选择"
                  :options="couponList"
                  :props="{ value: 'id', label: 'couponName' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item
                label="跳转至"
                :prop="`couponIdList.${index}.sourceId`"
                verify
              >
                <GlobalSearch
                  v-model="item.sourceId"
                  :type.sync="item.type"
                  :sourceId.sync="item.sourceId"
                  :sourceName.sync="item.sourceName"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="handleDeleteCoupon(index)"
              ></el-button>
            </el-col>
          </el-row>
        </div>

        <el-form-item
          label="场次对应的券标题"
          prop="couponTitle"
          :verify="{ maxLength: 8 }"
        >
          <el-input
            v-model="form.data.couponTitle"
            placeholder="请输入场次对应的券标题"
          />
        </el-form-item>
        <el-form-item
          label="场次对应的券说明"
          prop="couponDescription"
          :verify="{ maxLength: 20 }"
        >
          <el-input
            v-model="form.data.couponDescription"
            placeholder="请输入场次对应的券说明"
          />
        </el-form-item>

        <el-form-item label="抢券起止时间" prop="endTime" verify>
          <time-range-picker
            type="date-time"
            :start.sync="form.data.startTime"
            :end.sync="form.data.endTime"
          />
        </el-form-item>
        <el-form-item label="logo" prop="logo" verify>
          <Imgpond v-model="form.data.logo" aspectRatio="240/362" :count="1" />
        </el-form-item>

        <el-form-item label="场次规则录入" prop="rule" verify>
          <MiniMCE v-model="form.data.rule" :disabled="form.status === 'r'" />
        </el-form-item>
      </template>
    </KiFormDialog>
  </div>
</template>

<script>
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'

export default {
  mixins: [pageMixin],
  created () {
    this.getCouponList()
    this.getActivity()
    if (this.$route.query.groupId) {
      this.$nextTick(() => {
        this.$set(this.list.filter, 'groupId', this.$route.query.groupId)
      })
    }
  },
  setup: () =>
    useAdmateAdapter({
      urlPrefix: 'one-travel-api/couponActivity',
      list: {
        filter: {
          descs: ['create_time']
        }
      },
      form: {
        data: {
          couponIdList: []
        }
      }
    }),
  data () {
    return {
      sessionTypes: [
        { dataName: '随机领券', dataValue: 1 },
        { dataName: '固定领券', dataValue: 2 }
      ],
      couponList: [],
      activityList: [],
      sessionStatusList: [
        { dataName: '未开始', dataValue: '0', dataType: undefined },
        { dataName: '进行中', dataValue: '1', dataType: 'success' },
        { dataName: '已过期', dataValue: '2', dataType: 'danger' }
      ]
    }
  },
  watch: {
    'list.data' (nv, ov) {
      if (nv !== undefined) {
        let nowDate = this.$dayjs().format('YYYY-MM-DD HH:mm:ss')
        nv.forEach(its => {
          let date = this.autoFrontStatus(nowDate, its)
          its.sessionStatusValue = date.dataValue
          its.sessionStatusName = date.dataName
          its.sessionStatusType = date.dataType
          return its
        })
      }
    }
  },
  methods: {
    getActivity () {
      return this.$POST(
        'one-travel-api/couponActivityGroup/queryForList',
        {}
      ).then(res => {
        this.activityList = res.data
      })
    },
    getCouponList () {
      this.$POST('one-travel-api/coupon/queryForList', {}).then(res => {
        this.couponList = res.data
      })
    },
    submit () {
      if (
        this.form.data.couponIdList.length == 1 &&
        this.form.data.sessionType != 2
      ) {
        this.$swal.warning('若优惠券只有一张，请使用【固定发券】类型')
        return {
          show: true,
        }
      }
      return this.submitForm()
    },
    autoFrontStatus (nowDate, item) {
      // 未开始
      if (nowDate < item.startTime) {
        return this.sessionStatusList[0]
      }
      // 已过期
      else if (nowDate > item.endTime) {
        return this.sessionStatusList[2]
      } else {
        return this.sessionStatusList[1]
      }
    },
    handleAddCoupon () {
      this.form.data.couponIdList.push({
        couponId: ''
      })
    },
    handleDeleteCoupon (index) {
      this.form.data.couponIdList.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.info-warning {
  color: #409eff;
  line-height: 25px;
  letter-spacing: 1px;
  padding: 0;
  margin: 12px 0 0;
}
</style>
